package org.example.his.common.api;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

public class RequestUtils {

    public static String sendGet(String url, String param) throws IOException {
        InputStream inputStream = null;
        URL realUrl = new URL(url + "?" + param);
        URLConnection connection = realUrl.openConnection();
        //设置超时时间
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(15000);
        connection.connect();
        inputStream = connection.getInputStream();
        byte[] bytes = new byte[1024 * 1024 * 1024];
        StringBuilder result = new StringBuilder();
        int len;
        while ((len = inputStream.read(bytes)) != -1) {
            result.append(new String(bytes, 0, len));
        }
        if (inputStream != null) {
            inputStream.close();
        }
        return result.toString();
    }

    /**
     * 向post
     */
    public static String sendPost(String url, String param) throws IOException {
        InputStream inputStream = null;
        URL realUrl = new URL(url);
        URLConnection connection = realUrl.openConnection();
        connection.setConnectTimeout(30000);
        connection.setReadTimeout(30000);
        //post请求
        connection.setDoOutput(true);
        connection.setDoInput(true);
        OutputStream outputStream = connection.getOutputStream();
        outputStream.write(param.getBytes());
        outputStream.close();
        //请求数据
        inputStream = connection.getInputStream();
        byte[] bytes = new byte[1024 * 1024];
        int len;
        StringBuilder result = new StringBuilder();
        while ((len = inputStream.read(bytes)) != -1) {
            result.append(new String(bytes, 0, len));
        }
        if (inputStream != null) {
            inputStream.close();
        }
        return result.toString();
    }
}
